package com.util;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.DialogFragment;

import com.myapp.MyApp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xiaochun.hxhj.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


/**
 * Created by fei on 2017/6/20.
 */

public class CommentDialog extends DialogFragment {


    private boolean isCommenting = false;

    private ImageView img_colse;
    public TextView tv_buy;
    public TextView tv_buy_now;
    public EditText et_xlh;
    private View view;
    private Context context;
    private String token;
    private MyApp myApp;
    public String bindtitle;
    public String bindtitle_desc;
    private JSONObject params;
    private IWXAPI api;
    private String is_vip;

    public CommentDialog(Context context, String token, MyApp myApp,String is_vip) {
        this.context = context;
        this.token = token;
        this.myApp = myApp;
        this.is_vip = is_vip;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这句代码的意思是让dialogFragment弹出时沾满全屏
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.popup_buy_course, null);
        //让DialogFragment的背景为透明
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        initView(view);
        initEvent();
        return view;
    }

    //初始化view
    private void initView(View view) {
        img_colse = (ImageView) view.findViewById(R.id.img_colse);
        tv_buy = (TextView) view.findViewById(R.id.tv_buy);
        tv_buy_now = (TextView) view.findViewById(R.id.tv_buy_now);
        et_xlh = (EditText) view.findViewById(R.id.et_xlh);
        if ("1".equals(is_vip)) {
            //是会员
            tv_buy_now.setText("立即续费");
            tv_buy.setText("序列号续费");
        }else if ("0".equals(is_vip)){
            //不是会员
            tv_buy_now.setText("立即开通");
            tv_buy.setText("序列号开通");
        }
    }

    private void initEvent() {

        img_colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        tv_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = et_xlh.getText().toString().trim();
                if ("".equals(trim)){
                    ToastUtils.show("请输入会员序列号");
                }else{
                    bindVip(trim);
                }
            }
        });
        tv_buy_now.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindVipByWX();

            }
        });

    }
    public void bindVip(String no) {
        String url = myApp.getWebConfig() + "/api/vip/bind";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("card_no", no);
        MyLog.e("绑定会员卡",url+"   token="+token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }


                    JSONObject data = jsonObject.getJSONObject("data");
                    bindtitle = data.getString("title");
                    bindtitle_desc = data.getString("title_desc");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public void bindVipByWX() {
        String url = myApp.getWebConfig() + "/api/vip/payvip";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        MyLog.e("绑定会员卡",url+"   token="+token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }


                    JSONObject data = jsonObject.getJSONObject("data");
                    bindtitle = data.getString("title");
                    bindtitle_desc = data.getString("title_desc");
                    params = data.getJSONObject("params");
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obja = (String) msg.obj;
                    ToastUtils.show(obja);

                    break;
                case 1:

                    break;
                case 3:
//                    mPopupWindow.dismiss();
//                    bindsuccess();

                    EventBus.getDefault().post(new InfoEventMessage("开通会员成功",bindtitle+"="+bindtitle_desc));

                    break;
                case 4:
                    try {
                        JSONObject obj = params;
                        String appid = obj.getString("appid");
                        String partnerid = obj.getString("partnerid");
                        String prepayid = obj.getString("prepayid");
                        String timestamp = obj.getString("timestamp");
                        String noncestr = obj.getString("noncestr");
                        String packagewx = obj.getString("package");
                        String sign = obj.getString("sign");

                        PayReq req = new PayReq();

                        req.appId = appid;
                        req.partnerId = partnerid;
                        req.prepayId = prepayid;
                        req.nonceStr = noncestr;
                        req.timeStamp = timestamp;
                        req.packageValue = packagewx;
                        req.sign = sign;
                        //req.extData = "app data"; // optional
                        ToastUtils.show("支付中");
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

                        api = WXAPIFactory.createWXAPI(context, req.appId);
                        api.registerApp(req.appId);
                        api.sendReq(req);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;


            }
        }
    };



}
